package main

import (
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"github.com/jinzhu/gorm"
	"time"
)




//默认的表明就是`users`

//设置表名
func(User)TableName() string{
	return "profiles"
}

func(u User)TableName1() string{
	if u.Role =="admin" {
		return "profiles"
	}else{
		return "profiles1"
	}
}



type Animal struct {
	AnimalID int64 `gorm:"column:beast_id"` // 设置列名为 `beast_id`
	Birthday time.Time `gorm:"column:day_of_the_beast"`
	Age int64 `gorm:"column:age_of_the_beast"`


}


type User struct {
	gorm.Model

	Password []byte
	AnimalID int64 `gorm:"primary_key"`
	Code string
	Price uint
	Name string `gorm:"unique; not null"`
	Num int  `gorm:"AUTO_INCREMENT"`   //指定一个列的数据是否自增
    Email  string  `gorm:"type:varchan(100);unique_index"`
	Role string
}

func main() {
  db,err := gorm.Open("mysql","root:123@tcp(127.0.0.1:3306)/test?charset=utf8&parseTime=True&loc=Local")
	// 如果设置禁用表名复数形式属性为 true，`User` 的表名将是 `user`
  db.SingularTable(true)
	if err !=nil {
		panic(err)
	}
	defer db.Close()
	var user User
	fmt.Println(db.HasTable(user))
   var phone ="123456"
   err = db.Where("phone=?",phone).Find(&user).Error
	if err !=nil {
		fmt.Println(err)
	}
	err=db.Delete(&user).Error
	if err !=nil{
		fmt.Println(err)
	}
	//自动检查 Product 结构是否变化，变化则进行迁移
	db.AutoMigrate(&User{})
	db.Create(&User{Code: "L1212", Price: 1000})
    db.First(&user,1)
	db.First(&user,"code =?","L1212")

	db.Model(&user).Update("Price",2000)

	db.Delete(&user)


	// 用 `User` 结构体创建 `delete_users` 表
	db.Table("user").CreateTable(&User{})

	var delete_userrs []User
	db.Table("delete_userrs").Find(&delete_userrs)

	//修改默认表名
	gorm.DefaultTableNameHandler = func (db *gorm.DB, defaultTableName string) string  {
		return "prefix_" + defaultTableName;
	}

}
